<?php
class ActusController extends Controller{

	function index(){
			$perPage = 5;
			$this->loadModel('Actualite');
			$condition = array('online' => 1,'type'=>'actu');
			$d['actus'] = $this->Actualite->find(array(
				'conditions' => $condition,
				'orderd'	 => 'date', 
				'limit' => ($perPage*($this->request->page-1)).','.$perPage
					));
			$d['total'] = $this->Actualite->findCount($condition);
			$d['page'] = ceil($d['total'] / $perPage);
			$this->set($d);
		}



	function view($id,$slug){
		$this->loadModel('Actualite');
		
		$d['actus'] = $this->Actualite->findFirst( array(
			'fields' 	 => 'id,slug,description,titre',
			'conditions' => array('online' => 1,'id'=>$id,'type'=>'actu'),
			'orderd'	 => 'date', 
				));
		
		if(empty($d['actus'])){
			$this->e404('Page introuvable');
		}
		if ($slug != $d['actus']->slug) {
			$this->redirect("actus/view/$id/".$d['actus']->slug,301);
		}

		$this->set($d);
	}


	/**
	* ADMIN
	**/
	function admin_index(){
		$perPage = 10;
		$this->loadModel('Actualite'); 
		$condition = array('type'=>'actu');
		$d['actus'] = $this->Actualite->find(array(
			'fields' 	 => 'id,titre,online',
			'conditions' => $condition,
			'limit' 	 => ($perPage*($this->request->page-1)).','.$perPage,
			'orderd'	 => 'date',
			));
		$d['total'] = $this->Actualite->findCount($condition);
		$d['page'] = ceil($d['total'] / $perPage);
		$this->set($d);
	}

	/**
	* Permet d'éditer une actu
	**/
	function admin_edit($id = null){
		$this->loadModel('Actualite');
		if($id === null)
		{
			$actu = $this->Actualite->findFirst(array(
				'conditions' => array('online' => -1)
				));
			if(!empty($actu)){
				$id = $actu->id;
			}else{
				$this->Actualite->save(array(
					'online' => -1,
					));
				$id = $this->Actualite->id;
			}
		}
		//debug($this->request->data);
		$d['id']= $id;
		if ($this->request->data){
			$this->request->data->type = 'actu';
			$this->request->data->date = date('Y-m-d h:i:s');

			$this->Actualite->save($this->request->data);
			$this->Session->setFlash('Le contenu a bien été modifié','alert-success');
			$id = $this->Actualite->id;
			$this->redirect('admin/actus/index');	
		}
		else{
			$this->request->data = $this->Actualite->findFirst(array(
				'conditions' => array('id'=>$id)
				));
		}
		$this->set($d);
	}

	/**
	* Permet de supprimer une actu
	**/
	function admin_delete($id){
		$this->loadModel('Actualite');
		$this->Actualite->delete($id);
		$this->Session->setFlash('Le contenu a bien été supprimé','alert-success');
		$this->redirect('admin/actus/index');
	}

	/**
	* Permet de lister les  contenus
	**/
	function admin_tinymce(){
		$this->loadModel('Actualite');
		$this->layout = 'modal';
		$d['actus'] = $this->Actualite->find();
		$this->set($d);
	}

}
?>